#include "AppCrash.h"

#include <QtCore>
#if QT_VERSION >= 0x050000
#include <QtWidgets/QApplication>
#else
#include <QtGui/QApplication>
#include <QtGui/QMessageBox>
#endif
#include <QProcess>

#define APP_VERSION "5.1.46.2"

#ifdef WIN32
LONG WINAPI ApplicationCrashHandler(EXCEPTION_POINTERS* pExceptionInfo)
{

    char szFilePath[MAX_PATH + 1]={0};
    GetModuleFileNameA(NULL, szFilePath, MAX_PATH);
    (strrchr(szFilePath, '\\'))[0] = 0;
    char buffer[512] = {0};
    sprintf(buffer, "%s%s%s%s%s%s",szFilePath,"\\VZanMsWinRTCSdk-Demo ",APP_VERSION,"_",Time2LongStr(time(NULL)).c_str(),".dmp");
    qDebug()<<"buffer:"<<buffer;
    HANDLE hDumpFile = CreateFileA(buffer, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
    dumpInfo.ExceptionPointers = pExceptionInfo;
    dumpInfo.ThreadId = GetCurrentThreadId();
    dumpInfo.ClientPointers = TRUE;
//    MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpWithFullMemoryInfo, &dumpInfo, NULL, NULL);
    MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpWithDataSegs, &dumpInfo, NULL, NULL);
    CloseHandle(hDumpFile);


    //QMessageBox::information(0,"dd","dd");
    //QProcess::startDetached(qApp->applicationFilePath(), QStringList()<<"crash_restart");


    return EXCEPTION_EXECUTE_HANDLER;
}

#endif

std::string Time2LongStr(time_t intime)
{
    std::string timestr;
    if (intime == 0) {
        timestr = "00000000000000";
    } else {
        struct tm tmbuf;
        char buffer[20] = { };
#ifdef WIN32
        localtime_s(&tmbuf, &intime);
#else
        localtime_r(&intime, &tmbuf);
#endif
        sprintf(buffer, "%04d%02d%02d%02d%02d%02d", tmbuf.tm_year + 1900, tmbuf.tm_mon + 1, tmbuf.tm_mday, tmbuf.tm_hour, tmbuf.tm_min, tmbuf.tm_sec);
        timestr = buffer;
    }
    return timestr;
}

